package com.sptpc.demo1.controller;

import com.sptpc.demo1.model.Category;
import com.sptpc.demo1.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@Service
@RequestMapping("/category")
public class CategoryContronller {
    @Autowired
    public ICategoryService categoryService;

    //查询所有数据
    @GetMapping("/")
    public List<Category> gatAll() {
        List<Category> all = categoryService.gatALLCategory();
        return all;
    }

    //新增
    @PostMapping("/")
    public Category addNewCategory(@RequestBody @Valid Category category,
                                   BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError allError : bindingResult.getAllErrors()) {
                log.error(allError.toString());
            }
            return null;
        } else {
            log.info("新增饮品{}", category);
            categoryService.addNewCategory(category);
            return category;
        }
    }

    //查询
    @GetMapping("select/{id}")
    public Category selectCategory(@PathVariable Integer id) {
        return categoryService.selectbyID(id);
    }

    //删除
    @DeleteMapping("del/{id}")
    public void deleteByID(@PathVariable Integer id) {
        if (categoryService.selectbyID(id).equals(null)) {
            return;
        } else {
            categoryService.delcategoryByid(id);
        }
    }

    //修改
    @PutMapping("/")
    public Category setCategory(@RequestBody Category request) {
        log.info("修改饮品{}", request);
        Category category = categoryService.selectbyID(request.id);
        BeanUtils.copyProperties(request, category);
        categoryService.setCategory(category);
        return category;
    }


}
